package day04;

import com.blackhorse.annotation.dao.AUserMapper;
import com.blackhorse.domain.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;

/**
 * 使用注解开发实现单表CRUD
 */
public class Demo3_AnnotationCRUD {
    private SqlSessionFactory sqlSessionFactory;
    private SqlSession sqlSession;
    private AUserMapper userMapper;

    @Before
    public void init() {
        try {
            InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
            SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
            sqlSessionFactory = builder.build(in);
            sqlSession = sqlSessionFactory.openSession();
            userMapper = sqlSession.getMapper(AUserMapper.class);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @After
    public void destory() {
        sqlSession.commit();
        if (sqlSession != null) {
            sqlSession.close();
        }
    }

    //查询所有
    @Test
    public void testFindAll() {
        List<User> users = userMapper.findAll();
        for (User user : users) {
            System.out.println(user);
        }
    }

    @Test
    public void testFindById() {
        User user = userMapper.findById(2);
        System.out.println(user);
    }

    @Test
    public void testInsertUser() {
        User user = new User();
        user.setUsername("注解的新用户");
        user.setSex("男");
        user.setBirthday(new Date());
        user.setAddress("不知道什么地址");
        userMapper.saveUser(user);
    }

    @Test
    public void testUpdateUser() {
        User user = new User();
        user.setUsername("修改的注解用户");
        user.setSex("男");
        user.setBirthday(new Date());
        user.setAddress("依然不知道什么地址");
        user.setId(11);
        userMapper.updateUser(user);
    }

    @Test
    public void testDeleteUser() {
        userMapper.deleteUserById(10);
    }

    @Test//模糊查询
    public void testFindByName() {
        List<User> users = userMapper.findByName("张");
        for (User user : users) {
            System.out.println(user);
        }
    }

    //聚合函数查询
    @Test
    public void testFindTotal() {
        int total = userMapper.findTotal();
        System.out.println("总记录数：" + total);
    }

    //使用注解的ResultMap
    @Test
    public void testFindAllWithResultMap() {
        List<User> users = userMapper.findAllWithResultMap();
        for (User user : users) {
            System.out.println(user);
        }
    }
    //使用注解的ResultMap
    @Test
    public void testFindOneWithResultMap() {
        User user = userMapper.findByIdWithResultMap(2);
        System.out.println(user);
    }
}
